package com._21cn.cms.yellow.web.controller;

import com._21cn.cms.common.FormSelector;
import com._21cn.cms.resource.utils.PictureUtil;
import com._21cn.cms.yellow.entity.YellowPage;
import com._21cn.cms.yellow.entity.YellowPageCate;
import com._21cn.cms.yellow.entity.YellowPagePicture;
import com._21cn.cms.yellow.service.YellowPageCateService;
import com._21cn.cms.yellow.service.YellowPagePictureService;
import com._21cn.cms.yellow.service.YellowPageService;
import com._21cn.framework.base.controller.BaseController;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping({"/admin/yellow/yellowPage"})
public class YellowPageController extends BaseController
{
    private static String listView = "/admin/yellow/yellowPage/list";
    private static String showView = "/admin/yellow/yellowPage/show";
    private static String jsonView = "/admin/yellow/yellowPage/json";
    private static String formView = "/admin/yellow/yellowPage/form";
    private static String redirectListView = "redirect:/admin/yellow/yellowPage/list.do";

    private Map<String, String> propertyTitleMap = null;

    @Autowired
    private YellowPageService yellowPageService;

    @Autowired
    private YellowPageCateService yellowPageCateService;

    @Autowired
    private YellowPagePictureService yellowPagePictureService;

    @Autowired(required=false)
    @Qualifier("yellowPageValidator")
    private Validator yellowPageValidator;

    @RequestMapping({"/list"})
    public String listYellowPage(HttpServletRequest request, HttpServletResponse response, ModelMap model) { HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", listView);
        setRequestModelMap(request, model, true);
        model.addAttribute("statusMap", FormSelector.getStatusMap());
        return view; }

    @RequestMapping({"/search"})
    public String searchYellowPage(HttpServletRequest request, HttpServletResponse response, ModelMap model)
    {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", jsonView);
        setRequestModelMap(request, model, true);
        PageList result = getPageList(model);
        model.addAttribute("objListJson", JSON.toJSONString(result, new SerializerFeature[] { SerializerFeature.WriteDateUseDateFormat }));
        return view;
    }

    @RequestMapping({"/show"})
    public String showYellowPage(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", showView);
        Integer id = Integer.valueOf(reqInfo.getIntParameter("id", -1));
        if (id.intValue() > 0) {
            YellowPage yellowPage = this.yellowPageService.getById(id);
            if (yellowPage == null) {
                model.put("error.param.wrong", "无效参数");
            }

            model.addAttribute("yellowPage", yellowPage);
        }
        setRequestModelMap(request, model);
        return view;
    }

    @RequestMapping({"/edit"})
    public String editYellowPage(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter("view", formView);
        Integer id = Integer.valueOf(reqInfo.getIntParameter("id", -1));
        YellowPage yellowPage = new YellowPage();
        if (id.intValue() > 0) {
            yellowPage = this.yellowPageService.getById(id);
            if (yellowPage == null) {
                model.put("error.param.wrong", "无效参数");
            }
            Map paramMap = new HashMap();
            paramMap.put("eqYellowPageId", yellowPage.getId());
            List<YellowPageCate> cateList = this.yellowPageCateService.getList(paramMap, 1, 10);
            List cateIdList = new ArrayList();
            for (YellowPageCate yellowPageCate : cateList) {
                cateIdList.add(yellowPageCate.getYellowCateId());
            }
            yellowPage.setCateIdList(cateIdList);

            paramMap.clear();
            paramMap.put("eqYellowPageId", yellowPage.getId());
            Object yellowPagePictureList = this.yellowPagePictureService.getList(paramMap, 1, 10);
            yellowPage.setYellowPagePictureList((List)yellowPagePictureList);
        }
        model.addAttribute("yellowPage", yellowPage);

        setRequestModelMap(request, model);
        return view;
    }

    @RequestMapping({"/save"})
    public String saveYellowPage(HttpServletRequest request, ModelMap model) {
        String[] cateIdAry = request.getParameterValues("cateId");
        String[] imgUrls = request.getParameterValues("thumbPicUrl");
        String firstPicUrl = request.getParameter("firstPicUrl");
        String position = request.getParameter("position");
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer id = Integer.valueOf(reqInfo.getIntParameter("id", -1));

        String longPos = "";
        String dimPos = "";
        if (!StringUtil.isEmpty(position)) {
            String[] posAry = position.split(",");
            if ((posAry != null) && (posAry.length > 1)) {
                longPos = posAry[0];
                dimPos = posAry[1];
            }
        }
        if (id.intValue() > 0) {
            YellowPage yellowPage = this.yellowPageService.getById(id);
            if (bind(request, yellowPage, model, new Validator[] { this.yellowPageValidator }).hasErrors()) {
                return formView;
            }
            if(StringUtil.isEmpty(firstPicUrl) && imgUrls!=null && imgUrls.length>0 ){
                yellowPage.setFirstPicUrl(imgUrls[0]);
            }
            yellowPage.setLongPos(longPos);
            yellowPage.setDimPos(dimPos);
            yellowPage.setModifyTime(new Date());
            this.yellowPageService.update(yellowPage);
            if ((cateIdAry != null) && (cateIdAry.length > 0)) {
                Map paramMap = new HashMap();
                paramMap.put("eqYellowPageId", yellowPage.getId());
                this.yellowPageCateService.delete(paramMap);
                insertPageCate(yellowPage, cateIdAry);
            }
            if ((imgUrls != null) && (imgUrls.length > 0)) {
                Map paramMap = new HashMap();
                paramMap.put("eqYellowPageId", yellowPage.getId());
                this.yellowPagePictureService.delete(paramMap);
                insertPagePicture(yellowPage, imgUrls);
            }
        } else {
            YellowPage yellowPage = new YellowPage();
            if (bind(request, yellowPage, model, new Validator[] { this.yellowPageValidator }).hasErrors()) {
                return formView;
            }
            if(StringUtil.isEmpty(firstPicUrl) && imgUrls!=null && imgUrls.length>0 ){
                yellowPage.setFirstPicUrl(imgUrls[0]);
            }
            yellowPage.setLongPos(longPos);
            yellowPage.setDimPos(dimPos);
            this.yellowPageService.insert(yellowPage);
            insertPageCate(yellowPage, cateIdAry);
            insertPagePicture(yellowPage, imgUrls);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
    }

    private void insertPagePicture(YellowPage yellowPage, String[] imgUrls) {
        if (imgUrls == null) {
            return;
        }
        int i = 0;
        for (String imgUrl : imgUrls) {
            YellowPagePicture yellowPagePicture = new YellowPagePicture();
            yellowPagePicture.setYellowPageId(yellowPage.getId());
            yellowPagePicture.setPicUrl(imgUrl);
            yellowPagePicture.setOrderNum(Integer.valueOf(++i));
            String hashCode = PictureUtil.getHashCodeFromUrl(yellowPagePicture.getPicUrl());
            yellowPagePicture.setPicHashcode(hashCode);
            yellowPagePicture.setStatus(Integer.valueOf(1));
            this.yellowPagePictureService.insert(yellowPagePicture);
        }
    }

    private void insertPageCate(YellowPage yellowPage, String[] cateIdAry) {
        if (cateIdAry == null) {
            return;
        }
        for (String cateIdStr : cateIdAry)
            if (StringUtil.isNumber(cateIdStr)) {
                YellowPageCate yellowPageCate = new YellowPageCate();
                yellowPageCate.setYellowCateId(Integer.valueOf(cateIdStr));
                yellowPageCate.setYellowPageId(yellowPage.getId());
                this.yellowPageCateService.insert(yellowPageCate);
            }
    }

    @RequestMapping({"/updateStatus"})
    public String updateYellowPageStatus(HttpServletRequest request, HttpServletResponse response, ModelMap model)
    {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = Integer.valueOf(reqInfo.getIntParameter("status", -1));
        if (status.intValue() < 0) {
            model.clear();
            return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
        }
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds(reqInfo, model);
        if (objectIds.length() > 0) {
            this.yellowPageService.update(model);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
    }

    @RequestMapping({"/delete"})
    public String deleteYellowPage(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds(reqInfo, model);
        if (objectIds.length() > 0) {
            this.yellowPageService.delete(model);
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter("queryParam", "");
    }

    private PageList<YellowPage> getPageList(ModelMap model) {
        if (model.containsKey("likeName"))
            model.put("likeName", model.get("likeName").toString().toLowerCase());
        model.addAttribute("orderByClause", "ID desc");
        PageList yellowPageList = this.yellowPageService.getList(model, Integer.parseInt(model.get("pageNo").toString()), Integer.parseInt(model.get("pageSize").toString()));
        model.addAttribute("yellowPageList", yellowPageList);
        model.addAttribute("objList", yellowPageList);
        model.addAttribute("pageTurn", yellowPageList.getPageTurn());
        model.addAttribute("titleMap", getPropertyTitleMap());
        return yellowPageList;
    }

    private Map<String, String> getPropertyTitleMap() {
        if (this.propertyTitleMap == null) {
            this.propertyTitleMap = new HashMap();
            this.propertyTitleMap.put("id", "id");
            this.propertyTitleMap.put("name", "name");
            this.propertyTitleMap.put("nameShort", "nameShort");
            this.propertyTitleMap.put("mainProduct", "mainProduct");
            this.propertyTitleMap.put("mainUrl", "mainUrl");
            this.propertyTitleMap.put("introduce", "introduce");
            this.propertyTitleMap.put("address", "address");
            this.propertyTitleMap.put("linePhone", "linePhone");
            this.propertyTitleMap.put("telPhone", "telPhone");
            this.propertyTitleMap.put("contactMan", "contactMan");
            this.propertyTitleMap.put("email", "email");
            this.propertyTitleMap.put("postCode", "postCode");
            this.propertyTitleMap.put("qq", "qq");
            this.propertyTitleMap.put("longPos", "longPos");
            this.propertyTitleMap.put("dimPos", "dimPos");
            this.propertyTitleMap.put("status", "status");
            this.propertyTitleMap.put("topTime", "topTime");
            this.propertyTitleMap.put("createTime", "createTime");
            this.propertyTitleMap.put("modifyTime", "modifyTime");
            this.propertyTitleMap.put("createUserId", "createUserId");
            this.propertyTitleMap.put("modifyUserId", "modifyUserId");
        }
        return this.propertyTitleMap;
    }
}